using Microsoft.AspNetCore.Mvc;
using KnowledgeQA.Models.DTOs;
using KnowledgeQA.Services.Interfaces;

namespace KnowledgeQA.API.Controllers
{
    /// <summary>
    /// 文档管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class DocumentController : ControllerBase
    {
        private readonly IDocumentService _documentService;
        private readonly ILogger<DocumentController> _logger;

        public DocumentController(IDocumentService documentService, ILogger<DocumentController> logger)
        {
            _documentService = documentService;
            _logger = logger;
        }

        /// <summary>
        /// 获取文档列表
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>文档列表</returns>
        [HttpGet("list")]
        public async Task<ActionResult<PagedResponse<DocumentDTO>>> GetDocuments([FromQuery] DocumentQueryRequest request)
        {
            try
            {
                var result = await _documentService.GetDocumentsAsync(request);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取文档列表失败");
                return StatusCode(500, BaseResponse<List<DocumentDTO>>.ErrorResult("获取文档列表失败"));
            }
        }

        /// <summary>
        /// 根据ID获取文档
        /// </summary>
        /// <param name="id">文档ID</param>
        /// <returns>文档信息</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<DocumentDTO>> GetDocument(int id)
        {
            try
            {
                var document = await _documentService.GetDocumentByIdAsync(id);
                if (document == null)
                {
                    return NotFound(BaseResponse<DocumentDTO>.ErrorResult("文档不存在"));
                }
                return Ok(BaseResponse<DocumentDTO>.SuccessResult(document));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取文档失败，ID: {DocumentId}", id);
                return StatusCode(500, BaseResponse<DocumentDTO>.ErrorResult("获取文档失败"));
            }
        }

        /// <summary>
        /// 创建文档
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns>创建的文档</returns>
        [HttpPost]
        public async Task<ActionResult<DocumentDTO>> CreateDocument([FromBody] CreateDocumentRequest request)
        {
            try
            {
                var document = await _documentService.CreateDocumentAsync(request);
                return CreatedAtAction(nameof(GetDocument), new { id = document.Id }, 
                    BaseResponse<DocumentDTO>.SuccessResult(document));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建文档失败");
                return StatusCode(500, BaseResponse<DocumentDTO>.ErrorResult("创建文档失败"));
            }
        }

        /// <summary>
        /// 更新文档
        /// </summary>
        /// <param name="id">文档ID</param>
        /// <param name="request">更新请求</param>
        /// <returns>更新后的文档</returns>
        [HttpPut("{id}")]
        public async Task<ActionResult<DocumentDTO>> UpdateDocument(int id, [FromBody] UpdateDocumentRequest request)
        {
            try
            {
                var document = await _documentService.UpdateDocumentAsync(id, request);
                return Ok(BaseResponse<DocumentDTO>.SuccessResult(document));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新文档失败，ID: {DocumentId}", id);
                return StatusCode(500, BaseResponse<DocumentDTO>.ErrorResult("更新文档失败"));
            }
        }

        /// <summary>
        /// 删除文档
        /// </summary>
        /// <param name="id">文档ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult> DeleteDocument(int id)
        {
            try
            {
                var result = await _documentService.DeleteDocumentAsync(id);
                if (result)
                {
                    return Ok(BaseResponse<bool>.SuccessResult(true, "文档删除成功"));
                }
                return NotFound(BaseResponse<bool>.ErrorResult("文档不存在"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除文档失败，ID: {DocumentId}", id);
                return StatusCode(500, BaseResponse<bool>.ErrorResult("删除文档失败"));
            }
        }

        /// <summary>
        /// 上传文档文件
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="title">文档标题</param>
        /// <param name="description">文档描述</param>
        /// <param name="categoryId">分类ID</param>
        /// <param name="tags">标签（逗号分隔）</param>
        /// <returns>上传结果</returns>
        [HttpPost("upload")]
        public async Task<ActionResult<DocumentDTO>> UploadDocument(
            IFormFile file,
            [FromForm] string title,
            [FromForm] string? description = null,
            [FromForm] int? categoryId = null,
            [FromForm] string? tags = null)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(BaseResponse<DocumentDTO>.ErrorResult("请选择要上传的文件"));
                }
                _logger.LogInformation("上传文件 {title}", title);


                var request = new CreateDocumentRequest
                {
                    Title = title,
                    Description = description,
                    CategoryId = categoryId,
                    Tags = tags?.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List<string>()
                };

                var document = await _documentService.UploadDocumentAsync(file, request);
                return Ok(BaseResponse<DocumentDTO>.SuccessResult(document, "文档上传成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "上传文档失败");
                return StatusCode(500, BaseResponse<DocumentDTO>.ErrorResult("上传文档失败"));
            }
        }

        /// <summary>
        /// 批量上传文档
        /// </summary>
        /// <param name="files">文件列表</param>
        /// <param name="categoryId">分类ID</param>
        /// <returns>上传结果</returns>
        [HttpPost("batch-upload")]
        public async Task<ActionResult<List<DocumentDTO>>> BatchUploadDocuments(
            IFormFileCollection files,
            [FromForm] int? categoryId = null)
        {
            try
            {
                if (files == null || !files.Any())
                {
                    return BadRequest(BaseResponse<List<DocumentDTO>>.ErrorResult("请选择要上传的文件"));
                }

                var documents = await _documentService.BatchUploadDocumentsAsync(files, categoryId);
                return Ok(BaseResponse<List<DocumentDTO>>.SuccessResult(documents, "批量上传成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量上传文档失败");
                return StatusCode(500, BaseResponse<List<DocumentDTO>>.ErrorResult("批量上传文档失败"));
            }
        }

        /// <summary>
        /// 处理文档
        /// </summary>
        /// <param name="id">文档ID</param>
        /// <returns>处理结果</returns>
        [HttpPost("{id}/process")]
        public async Task<ActionResult> ProcessDocument(int id)
        {
            try
            {
                var result = await _documentService.ProcessDocumentAsync(id);
                if (result)
                {
                    return Ok(BaseResponse<bool>.SuccessResult(true, "文档处理成功"));
                }
                return BadRequest(BaseResponse<bool>.ErrorResult("文档处理失败"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理文档失败，ID: {DocumentId}", id);
                return StatusCode(500, BaseResponse<bool>.ErrorResult("处理文档失败"));
            }
        }

        /// <summary>
        /// 重新处理文档
        /// </summary>
        /// <param name="id">文档ID</param>
        /// <returns>处理结果</returns>
        [HttpPost("{id}/reprocess")]
        public async Task<ActionResult> ReprocessDocument(int id)
        {
            try
            {
                var result = await _documentService.ReprocessDocumentAsync(id);
                if (result)
                {
                    return Ok(BaseResponse<bool>.SuccessResult(true, "文档重新处理成功"));
                }
                return BadRequest(BaseResponse<bool>.ErrorResult("文档重新处理失败"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重新处理文档失败，ID: {DocumentId}", id);
                return StatusCode(500, BaseResponse<bool>.ErrorResult("重新处理文档失败"));
            }
        }

        /// <summary>
        /// 获取文档统计信息
        /// </summary>
        /// <returns>统计信息</returns>
        [HttpGet("stats")]
        public async Task<ActionResult<DocumentStats>> GetDocumentStats()
        {
            try
            {
                var stats = await _documentService.GetDocumentStatsAsync();
                return Ok(BaseResponse<DocumentStats>.SuccessResult(stats));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取文档统计信息失败");
                return StatusCode(500, BaseResponse<DocumentStats>.ErrorResult("获取文档统计信息失败"));
            }
        }
    }
} 